//
//  SignViewController.m
//  PlayerWorld
//
//  Created by 1 on 16/5/16.
//  Copyright © 2016年 刘成. All rights reserved.
//
#define UISCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define UISCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#import "SignViewController.h"
#import "MainTabBarController.h"
#import "ForgetPasswordViewController.h"

#import "AFNetworking.h"

#import "MBProgressHUD.h"

@interface SignViewController ()<UITextFieldDelegate>

@end

@implementation SignViewController
{
    MBProgressHUD *hud;
}
-(void)obtainData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";

    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"User" forKey:@"Model"];
    [parametersDic setObject:@"CheckUserLogin" forKey:@"Action"];
    [parametersDic setObject:_username.text forKey:@"username"];
    [parametersDic setObject:_password.text forKey:@"password"];
    [parametersDic setObject:_identifyingCode.text forKey:@"verification"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    // 解析成功隐藏系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([dic objectForKey:@"userid"]) {

            MainTabBarController *mTBC= [[MainTabBarController alloc] init];
            [self presentViewController:mTBC animated:YES completion:nil];
//            [self.navigationController pushViewController:mTBC animated:YES];
            [[NSUserDefaults standardUserDefaults]setValue:[dic objectForKey:@"userid"] forKey:@"123"];

        }else{

            UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"登录信息" message:[dic objectForKey:@"msg"]preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

            }];
            [alerView addAction:action];
            [self presentViewController:alerView animated:YES completion:nil];
        }
//        [hud hide:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    }];

}
#pragma mark -实时监测网络连接
-(void)wifi{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
//            NSLog(@"有网");
        }else
        {
//            NSLog(@"没有网");
            [hud hide:YES];
            UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"登录信息" message:@"网络未连接"preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alerView addAction:action];
            [self presentViewController:alerView animated:YES completion:nil];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.title = @"登陆";
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:36/255.0f green:11/255.0f blue:54/255.0f alpha:1];
//    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((UISCREEN_WIDTH-200)/2, 120, 200, 60)];
    [imageView setImage:[UIImage imageNamed:@"Signlogo"]];
    [imageView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:imageView];
    
//    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    _username = [[UITextField alloc]initWithFrame:CGRectMake(20,200, UISCREEN_WIDTH-20-20, 40)];
    [_username setBorderStyle:UITextBorderStyleBezel];
    _username.placeholder = @"用户名";
    _username.backgroundColor = [UIColor whiteColor];
    _username.delegate = self;
    [self.view addSubview:_username];
    
    _password = [[UITextField alloc]initWithFrame:CGRectMake(20,CGRectGetMaxY(_username.frame), UISCREEN_WIDTH-20-20, 40)];
    _password.backgroundColor = [UIColor whiteColor];
    [_password setBorderStyle:UITextBorderStyleBezel];
    _password.placeholder = @"密码";
    _password.delegate = self;
    [_password setSecureTextEntry:YES];
    [self.view addSubview:_password];

    _identifyingCode = [[UITextField alloc]initWithFrame:CGRectMake(20,CGRectGetMaxY(_password.frame)+10, UISCREEN_WIDTH-20-20-120-20, 40)];
    [_identifyingCode setBorderStyle:UITextBorderStyleBezel];
    _identifyingCode.backgroundColor = [UIColor whiteColor];
    _identifyingCode.placeholder = @"验证码";
    _identifyingCode.delegate = self;
    [self.view addSubview:_identifyingCode];

    // 验证码
    UIWebView *reCaptchaImageView = [[UIWebView alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH-20-120, CGRectGetMaxY(_password.frame)+10, 120, 40)];
    reCaptchaImageView.scalesPageToFit = YES;
    reCaptchaImageView.userInteractionEnabled = NO;
    NSURLRequest *reCaptchaurl = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.wjsj1.com:99?Model=Images&Action=SetCheckCode&a=userlogin&rand=1234"]];
    [reCaptchaImageView loadRequest:reCaptchaurl];

    [self.view addSubview:reCaptchaImageView];


//    UIButton *forgetPasswordButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [forgetPasswordButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
//    forgetPasswordButton.titleLabel.font = [UIFont systemFontOfSize:12];
//    [forgetPasswordButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [forgetPasswordButton addTarget:self action:@selector(forgetPasswordButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [forgetPasswordButton setFrame:CGRectMake(UISCREEN_WIDTH-20-80, CGRectGetMaxY(_identifyingCode.frame)+10, 80, 20)];
//    [forgetPasswordButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    [self.view addSubview:forgetPasswordButton];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTitle:@"登录" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(20, CGRectGetMaxY(_identifyingCode.frame)+10+10, UISCREEN_WIDTH-20-20, 40)];
    [btn setBackgroundColor:[UIColor colorWithRed:248/255.0f green:182/255.0f blue:43/255.0f alpha:1]];
    [self.view addSubview:btn];
    self.view.backgroundColor = [UIColor colorWithRed:36/255.0f green:11/255.0f blue:54/255.0f alpha:1];
}

- (void)login:(UIButton *)sender {
    
    [self obtainData];
}
- (void)forgetPasswordButtonAction:(UIButton *)sender {
  
    ForgetPasswordViewController *fPVC= [[ForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:fPVC animated:YES];
}

// 点击Return收起键盘
-(BOOL) textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

    return YES;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
}
@end
